<template>
  <div class="container">
    <el-row type="flex" justify="space-between">
      <div class="main">
        <h2>发表新攻略</h2>
        <p class="create-desc">
          分享你的个人游记，让更多人看到哦！
        </p>

        <el-form ref="form" :model="form">
          <el-form-item>
            <el-input
              v-model="form.postTitle"
              placeholder="请输入标题"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <client-only>
              <vue-editor
                v-model="form.postContent"
                :editor-toolbar="customToolbar"
              />
            </client-only>
          </el-form-item>
          <el-form-item label="选择城市">
            <el-autocomplete
              class="inline-input"
              v-model="form.postCity"
              :fetch-suggestions="queryDepartSearch"
              placeholder="请搜索游玩城市"
              :trigger-on-focus="false"
              @select="handleSelect"
            ></el-autocomplete>
          </el-form-item>
        </el-form>

        <div class="create-button">
          <el-button type="primary" size="small" @click="publishPost"
            >发布</el-button
          >
          <span class="submit-side">
            或者
            <a href="javascript:;" @click="saveDrafts">保存到草稿</a>
          </span>
        </div>

        <el-dialog
          title="提示"
          :visible.sync="dialogVisible"
          width="30%"
          height="5%"
        >
          <i style="color:#e6a23c" class="el-icon-warning"></i>
          <span>{{ postError }}</span>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="dialogVisible = false"
              >确 定</el-button
            >
          </span>
        </el-dialog>
      </div>

      <div class="aside">
        <div class="draft-box">
          <h4 class="draft-title">
            草稿箱（{{ this.$store.state.history.postList.length }}）
          </h4>

          <div class="draft-list">
            <div
              class="draft-item"
              v-for="(item, index) in draftList"
              :key="index"
            >
              <div class="draft-post-title" @click="getDraft(index)">
                {{ item.postTitle }}
              </div>
              <el-row type="flex" justify="space-between">
                <p>{{ item.time }}</p>
                <div>
                  <i class="iconfont el-icon-edit" @click="getDraft(index)"></i>
                  <i
                    class="iconfont el-icon-delete"
                    @click="delDraft(index)"
                  ></i>
                </div>
              </el-row>
            </div>
          </div>
        </div>
      </div>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogVisible: false,

      form: {
        postTitle: "",
        postContent: "",
        postCity: ""
      },

      customToolbar: [
        ["bold", "italic", "underline"],
        [{ list: "ordered" }, { list: "bullet" }],
        ["image", "code-block"]
      ],
      postError: ""
    };
  },
  methods: {
    publishPost() {
      if (this.form.postTitle === "") {
        this.dialogVisible = true;
        this.postError = "请填写标题";
        return;
      }
      if (this.form.postContent === "") {
        this.dialogVisible = true;
        this.postError = "请填写内容";
        return;
      }
      if (this.form.postCity === "") {
        this.dialogVisible = true;
        this.postError = "请填写城市";
        return;
      }

      this.$axios({
        url: "posts",
        method: "post",
        data: {
          content: this.form.postContent,
          title: this.form.postTitle,
          city: this.form.postCity
        },
        headers: {
          // 完整的格式需要 Bearer 前缀
          // Authorization: 'Bearer xxxxxx'
          Authorization: "Bearer" + " " + this.$store.state.user.userInfo.token
        }
      }).then(res => {
        console.log(res.data);
        this.$message.success("发布成功");
        this.form = {
          postTitle: "",
          postContent: "",
          postCity: ""
        };
        // this.$router.push("/post");
      });
    },

    getCityList() {
      return this.$axios({
        url: "/cities",
        params: {
          name: this.form.postCity
        }
      }).then(res => {
        console.log(res.data);

        const suggestions = res.data.data.map(city => {
          return {
            value: city.name.replace(/市$/, ""),
            code: city.sort
          };
        });

        return suggestions.filter(city => {
          return city.code;
        });
      });
    },

    // 出发城市输入框获得焦点时触发
    // value 是选中的值，showList是回调函数，接收要展示的列表
    queryDepartSearch(value, showList) {
      this.getCityList(value).then(suggestions => {
        if (suggestions.length > 0) {
          // this.postCity = suggestions[0].code;
          showList(suggestions);
        } else {
          showList([
            {
              value: "没有找到该城市"
            }
          ]);
        }
      });
    },
    handleSelect(item) {
      console.log(item);
      this.form.postCity = item.value;
    },

    // 保存草稿到本地
    saveDrafts() {
      this.$store.commit("history/addDraftList", {
        form: this.form
      });

      // 清空输入框
      this.form = {
        title: "",
        content: "",
        city: ""
      };
    },
    getDraft(index) {
      console.log(123);
      this.form = { ...this.$store.state.history.postList[index] };
      console.log(this.form);
    },

    // 删除草稿
    delDraft(index) {
      this.$store.commit("history/delDraftList", {
        form: this.form
      });
    }
  },
  computed: {
    draftList() {
      return this.$store.state.history.postList;
    }
  },
  watch: {
    draftList() {
      return this.$store.state.history.postList;
    }
  }
};
</script>

<style lang="less" scoped>
.container {
  width: 1000px;
  margin: 0 auto;
  padding: 20px 0;
}

.main {
  width: 750px;
  h2 {
    font-weight: 400;
    font-size: 22px;
    margin-bottom: 10px;
  }

  .create-desc {
    font-size: 12px;
    color: #999;
    margin-bottom: 10px;
  }

  .submit-side {
    margin-left: 10px;
    font-size: 14px;

    a {
      color: orange;
    }
  }
}

.aside {
  width: 225px;

  .draft-box {
    border: 1px solid #ddd;
    padding: 10px;

    .draft-title {
      margin-bottom: 10px;
      font-weight: 400;
      color: #666;
    }
    .draft-item {
      margin-bottom: 10px;
      font-size: 14px;

      .draft-post-title {
        word-break: break-all;
        text-overflow: ellipsis;
        overflow: hidden;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        cursor: pointer;
      }

      p {
        color: #999;
      }

      .iconfont {
        cursor: pointer;
      }
    }
  }
}
</style>
